package com.example.app.Websocket;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.app.R;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Uploader extends AppCompatActivity {
    private static final int PICK_IMAGE = 1;
    private WebSocket webSocket;
    String token="4ebc3496-8b1f-4cfc-94eb-0dab6885b161";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.uploadtest);
        Button selectBtn = findViewById(R.id.selectButton);
        selectBtn.setOnClickListener(v -> openGallery());
        connectWebSocket();
    }
    private void connectWebSocket() {
        try {
            @SuppressLint("CustomX509TrustManager") TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            // 初始化SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            // 创建OkHttpClient并配置SSL
            OkHttpClient client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true) // 绕过主机名验证
                    .build();

            Request request = new Request.Builder()
                    .url("wss://192.168.33.43:443/upload")
                    .addHeader("Authorization", "Bearer " + token)  // 添加认证头
                    .build();
            webSocket = client.newWebSocket(request, new WebSocketListener() {
                @Override
                public void onOpen(WebSocket webSocket, Response response) {
                    runOnUiThread(() -> Toast.makeText(Uploader.this, "已连接服务器", Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onMessage(WebSocket webSocket, String text) {
                    runOnUiThread(() -> Toast.makeText(Uploader.this, "服务器: " + text, Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onClosed(WebSocket webSocket, int code, String reason) {
                    runOnUiThread(() -> Toast.makeText(Uploader.this, "连接关闭", Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
                    System.out.println("----------------"+t.getMessage()+"----------------------");
                    runOnUiThread(() -> Toast.makeText(Uploader.this, "连接失败: " + t.getMessage(), Toast.LENGTH_SHORT).show());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(() -> Toast.makeText(this, "SSL配置: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            try {
                InputStream inputStream = getContentResolver().openInputStream(imageUri);
                ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    byteBuffer.write(buffer, 0, len);
                }

                if (webSocket != null) {
                    webSocket.send(ByteString.of(byteBuffer.toByteArray()));

                    Toast.makeText(this, "图片发送中...", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "读取图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webSocket != null) {
            webSocket.close(1000, "正常关闭");
        }
    }
}